<template>
  <view>
    <nut-searchbar
      v-model="query.keywords"
      :placeholder="placeholder"
      confirm-type="search"
      @search="search"
      @change="searched = false"
    >
      <template #leftin>
        <nut-icon size="14" name="search2"></nut-icon>
      </template>
    </nut-searchbar>
    <view class="pa-2">
      <view v-if="protoTotal" class="tip-text px-4"
        >为您找到约<text style="font-weight: bold; color: #fa2c19; padding: 0 8px">{{ protoTotal }}</text
        >个商品</view
      >
      <proto-list :items="protoItems" @item-click="handleProtoClick" />
      <view v-if="!protoTotal && !query.keywords" class="height-50vh dpr-center-center tip-text"
        >请输入关键字搜索商品
      </view>
      <view v-if="searching" class="height-50vh dpr-center-center tip-text"><nut-icon name="loading1" />正在搜索 </view>
      <view>
        <nut-empty
          v-if="!searching && !protoTotal && query.keywords && searched"
          :description="`没有找到 ${query.keywords} 相关的商品`"
        />
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import Taro, { useLoad, useUnload } from '@tarojs/taro';
import ProtoList from '@/components/proto-list/index.vue';
import { getProtoListApi } from '@/api/proto';

const placeholder = ref('搜索商品店铺');
const placeholderList = ref([]);
const protoItems = ref([]);
const protoTotal = ref(0);
const query = ref({
  page: 1,
  limit: 20,
  keywords: '',
});
const searched = ref(false);
const searching = ref(false);
const search = () => {
  if (!query.value.keywords) {
    query.value.keywords = placeholder.value;
  }
  if (searching.value) {
    return;
  }
  searching.value = true;
  getProtoListApi(query.value)
    .then((res) => {
      protoItems.value = res.result.items;
      protoTotal.value = res.result.total;
    })
    .finally(() => {
      searched.value = true;
      searching.value = false;
    });
};
const handleProtoClick = (proto) => {
  Taro.navigateTo({ url: `/pages/proto/detail/index?id=${proto.id}` });
};
let timer = null;
const getHostSearch = () => {
  console.log('加载热搜');
  placeholderList.value = ['月饼', '红酒', '零食', '牛奶', '内衣'];
  if (timer) {
    return;
  }
  timer = setInterval(() => {
    const indexOf = placeholderList.value.indexOf(placeholder.value);
    placeholder.value = placeholderList.value[indexOf + 1];
  }, 2000);
};
useUnload(() => {
  console.log('useUnload');
  clearInterval(timer);
});
useLoad(() => {
  getHostSearch();
});

onMounted(() => {});

const clickLeft = () => {
  Taro.navigateBack();
};
</script>

<style lang="less" scoped></style>
